from datetime import datetime
from django.http import HttpResponse
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views.generic import View
import json

from rest_framework.viewsets import ModelViewSet
from booktest.models import BookInfo
from booktest.serializers import BookInfoSerializer


class BookInfoViewSet(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializer


class BooksAPIVIew(View):
    def get(self,request):
        # 查询所有图书
        queryset = BookInfo.objects.all()
        book_list = []
        for book in queryset:
            book_list.append({
                'id':book.id,
                'btitle':book.btitle,
                'bpub_date':book.bpub_date,
                'bread':book.bread,
                'bcomment':book.bcomment,
                'image':book.image.url if book.image else ''
            })
        return JsonResponse(book_list,safe=False)
    def post(self,request):
        # 新增图书  获取前端发来的二进制数据
        json_bytes = request.body
        # 把二进制数据转换成字符串
        json_str = json_bytes.decode()
        # 把字符串转成字典
        book_dict = json.loads(json_str)
#         把数据同步到数据库
        book = BookInfo.objects.create(

            id = book_dict.get('id'),
            btitle=book_dict.get('btitle'),
            bpub_date=datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date(),

            bread = book_dict.get('bread'),
            bcomment = book_dict.get('bcomment'),
            # "image": ""
        )
#         返回响应
        response_book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }
        return JsonResponse(response_book_dict,status=201)

#     返回单一对象，重新定义一个类
class BookAPIView(View):
    def get(self,request,pk):
#         获取单个图书信息
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        response_book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }


        return JsonResponse(response_book_dict)





    def put(self,request,pk):
#         接收字符串，转成字典
        json_bytes = request.body
        json_str = json_bytes.decode()
        book_dict = json.loads(json_str)
# 判断pk是否合法
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
# 修改数据
        book.btitle = book_dict.get('btitle')
        book.save()
# 构造json数据
        response_book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }
# 响应json数据
        return JsonResponse(response_book_dict)


    def delete(self,request,pk):
        # 判断pk是否合法
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 获取到的book删除
        book.delete()
        return HttpResponse(status=204)